<template>
  <div class="common-layout">
    <!-- 左侧边栏 -->
    <div :class="['sidebar', { 'collapsed': isCollapsed }]">
      <div class="sidebar-top">
        <!-- 折叠按钮 -->
        <div class="sidebar-header">
          <h2 class="sidebar-title" v-show="!isCollapsed">Sage</h2>
          <div class="collapse-btn" @click="toggleSidebar">
            <el-icon v-if="!isCollapsed">
              <Fold/>
            </el-icon>
            <el-icon v-else="isCollapsed">
              <Expand/>
            </el-icon>
          </div>
        </div>

        <!-- 新对话按钮 -->
        <div class="new-chat-btn" @click="startNewChat">
          <el-icon class="new-chat" :size="25">
            <ChatDotRound/>
          </el-icon>
          <span v-show="!isCollapsed">开启新对话</span>
        </div>

        <!-- 历史记录列表 -->
        <div class="chat-history" v-show="!isCollapsed">
          <div v-for="chat in chatHistory"
               :key="chat.sessionId"
               :class="['history-item', { 'active': activeSessionId === chat.sessionId }]"
               @click="openChat(chat)">
            <span class="history-title">{{ chat.title }}</span>
            <div class="history-actions">
              <span class="history-time">{{ chat.updateTime.split(' ')[0] }}</span>
              <el-dropdown trigger="click" @command="handleCommand($event, chat)" @click.stop>
                <el-icon class="more-icon" :size="28">
                  <MoreFilled/>
                </el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="rename">
                      <el-icon>
                        <Edit/>
                      </el-icon>
                      重命名
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <el-icon>
                        <Delete/>
                      </el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部用户信息 -->
      <div class="user-profile">
        <el-dropdown @command="handleSettingCommand" trigger="click">
          <div class="dropdown-trigger">
            <el-avatar
                class="user-img"
                :size="32"
                :src="userImage"
                @error="() => userImageLoadError = true">
              <!-- 头像加载失败时显示用户名首字母 -->
              <span v-if="userImageLoadError">{{ userName?.charAt(0)?.toUpperCase() || 'U' }}</span>
            </el-avatar>
            <span v-if="!isCollapsed" class="user-info">{{ userName || '个人信息' }}</span>
            <el-icon v-if="!isCollapsed" class="arrow-icon">
              <ArrowDown/>
            </el-icon>
          </div>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon>
                  <User/>
                </el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon>
                  <Tools/>
                </el-icon>
                系统设置
              </el-dropdown-item>
              <el-dropdown-item command="contact">
                <el-icon>
                  <Message/>
                </el-icon>
                意见反馈
              </el-dropdown-item>
              <el-dropdown-item command="logout" divided>
                <el-icon>
                  <SwitchButton/>
                </el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <template v-if="activeSessionId">
        <!-- 聊天界面 -->
        <chat-component
            ref="chatComponentRef"
            :sessionId="activeSessionId"
            :userAvatar="userAvatarSrc"
            :initialMessages="activeChat?.messages || []"
            :handleSession="handleMessageSent"
        />
      </template>
      <template v-else>
        <!-- 欢迎页面 -->
        <welcome-component
            :inputValue="inputMessage"
            :isSending="loading"
            @send="openNewSession"
        />
      </template>
    </div>

    <user-profile
        v-model:visible="profileDialogVisible"
        @profile-updated="handleProfileUpdated"
    />
  </div>
</template>

<script setup>
import {ref, nextTick, onMounted, watch} from 'vue'
import {dayjs, ElMessage, ElMessageBox} from 'element-plus'
import {icons} from '@/views/js'
import userStore from '@/store/user'
import { getSessions, deleteSession, updateSession} from "@/api";
import {useRouter, useRoute} from "vue-router";
import {removeToken} from "@/utils/auth";
import ChatComponent from '@/components/chat.vue';
import WelcomeComponent from '@/components/welcome.vue';
import {openNew} from "@/utils/sseClient";
import defaultAvatar from '@/assets/images/profile.jpg';
import UserProfile from '@/views/user/user.vue';

// 解构需要的图标
const {
  ChatDotRound,
  Setting,
  Position,
  Expand,
  Fold,
  Edit,
  Upload,
  Loading,
  MoreFilled,
  Delete,
  Tools,
  Message,
  SwitchButton,
  ArrowDown,
  User
} = icons

// 路由相关
const router = useRouter();
const route = useRoute();

// 状态变量
const isCollapsed = ref(false);
const inputMessage = ref('');
const chatHistory = ref([]);
const activeSessionId = ref(null);
const chatComponentRef = ref(null);

// 头像相关状态
const userImage = ref('');
const userName = ref('');
const userImageLoadError = ref(false);
const userAvatarSrc = ref(defaultAvatar);


// 个人信息弹窗相关
const profileDialogVisible = ref(false);

// 获取用户信息
const initUserInfo = async () => {
  try {
    // 先设置一个默认头像路径
    userImage.value = '/assets/images/profile.jpg';
    await userStore.getInfo();

    // 获取用户信息
    userImage.value = userStore.getAvatar();
    userAvatarSrc.value =  userStore.getAvatar(); //传给chat组件
    userName.value = userStore.getUserName();

    // 重置错误标志
    userImageLoadError.value = false;

    // 确保DOM更新
    await nextTick();
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败，请重新登录！");

    removeToken();
    router.push('/login').catch(err => {
      console.error("路由跳转失败:", err);
    });
  }
};

// 获取会话数据
const getSession = async () => {
  try {
    const userId = userStore.getUserId();

    if (!userId) {
      console.warn("用户ID为空，无法获取会话");
      return;
    }
    const res = await getSessions(userId);
    if (res.code === 200) {
      chatHistory.value = res.data || [];
    } else {
      ElMessage.error(res.msg || '获取会话列表失败');
    }
  } catch (error) {
    console.error("获取会话失败:", error);
    ElMessage.error("获取会话列表失败");
  }
};

// 监听路由参数，更新活动会话
watch(() => route.params.sessionId, (newSessionId) => {
  if (newSessionId) {
    activeSessionId.value = newSessionId;
  }
}, {immediate: true});

// 折叠侧边栏
const toggleSidebar = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 点击侧边栏的聊天记录，打开对应的会话
const openChat = (chat) => {
  activeSessionId.value = chat.sessionId;
// 使用router.push导航到/chat/sessionId路由
  router.push(`/chat/${chat.sessionId}`);
};
// 添加 activeChat 计算属性
const activeChat = computed(() => {
  return chatHistory.value.find(chat => chat.sessionId === activeSessionId.value) || null;
});


// 创建新会话数据对象
const getChatSession = (message) => {
  const now = dayjs().format('YYYY-MM-DD HH:mm:ss');
  // 创建第一条用户消息
  const firstMessage = {
    role: 'user',
    content: message,
    createTime: now,
    createBy: userStore.getUserName(),
    updateBy: userStore.getUserName(),
    updateTime: now,
    userId: userStore.getUserId(),
  };
  return {
    userId: userStore.getUserId(),
    createBy: userStore.getUserName(),
    createTime: now,
    updateBy: userStore.getUserName(),
    updateTime: now,
    messages: [firstMessage],
    content: message
  };
};

// 在欢迎窗口发送消息,生成新会话
const loading = ref();
const currentController = ref();
const openNewSession = async (message) => {
  if (!message.trim() || loading.value) return;

  // 设置加载状态
  loading.value = true;

  // 准备变量
  let aiResponse = '';

  try {
    // 清空输入框
    inputMessage.value = '';

    // 构建聊天会话对象
    const chatSession = getChatSession(message);

    // 创建请求对象
    const request = openNew(chatSession, {

      onSessionId: (sessionId) => {
        activeSessionId.value = sessionId;
        router.push(`/chat/${sessionId}`);

        // 创建新会话并添加到列表
        const newSession = {
          sessionId: sessionId,
          title: message.length <= 20 ? message : message.substring(0, 20) + "...",
          updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          createBy: userStore.getUserName(),
          userId: userStore.getUserId(),
          messages: [{
            role: 'user',
            content: message,
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            createBy: userStore.getUserName()
          }]
        };
        // 添加到会话列表首位
        chatHistory.value.unshift(newSession);
      },

      onMessage: (chunk) => {
        // 累积AI回复
        aiResponse += chunk;
        // 将消息片段实时传递给聊天组件
        if (chatComponentRef.value) {
          chatComponentRef.value.appendStreamingContent(chunk);
        }
      },

      // 增加onComplete处理
      onComplete: () => {
        // 会话创建完成后，如果需要可以刷新会话列表
        getSession();
        // 通知聊天组件完成流式传输
        if (chatComponentRef.value) {
          chatComponentRef.value.completeStreaming();
        }
        // 关闭加载状态
        loading.value = false;
      },

      onError: (error) => {
        console.error("创建会话失败:", error);
        ElMessage.error("创建会话失败，请重试");

        // 关闭加载状态
        loading.value = false;
      }
    });

    // 存储控制器，以便可能需要取消请求
    currentController.value = request;

    // 可以选择等待请求完成
    const result = await request.promise;
    console.log("请求完成，结果:", result);

  } catch (error) {
    // 这里会捕获未在回调中处理的错误
    console.error("创建会话过程中发生未处理的错误:", error);
    ElMessage.error("创建会话失败");
    loading.value = false;
  }
};

// 处理消息发送成功
const handleMessageSent = () => {
  // 可以在这里处理消息发送成功后的逻辑
  // 例如更新会话列表中的最后消息时间等
};

// 处理下拉菜单命令
const handleCommand = async (command, chat) => {
  switch (command) {
    case 'rename':
      // 重命名对话
      ElMessageBox.prompt('请输入新的对话名称', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: chat.title,
        inputPattern: /\S+/,
        inputErrorMessage: '名称不能为空'
      }).then(async ({value}) => {
        try {
          const res = await updateSession({
            sessionId: chat.sessionId,
            title: value
          });

          if (res.code === 200) {
            // 更新本地数据
            const index = chatHistory.value.findIndex(s => s.sessionId === chat.sessionId);
            if (index !== -1) {
              chatHistory.value[index].title = value;
            }
            ElMessage.success('重命名成功');
          } else {
            ElMessage.error(res.msg || '重命名失败');
          }
        } catch (error) {
          console.error("重命名失败:", error);
          ElMessage.error("重命名失败");
        }
      }).catch(() => {
      });
      break;

    case 'delete':
      // 删除对话
      ElMessageBox.confirm(
          '确定要删除此对话吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(async () => {
        try {
          const res = await deleteSession(chat.sessionId);

          if (res.code === 200) {
            // 从历史记录中移除
            chatHistory.value = chatHistory.value.filter(s => s.sessionId !== chat.sessionId);

            // 如果删除的是当前会话，回到欢迎页
            if (activeSessionId.value === chat.sessionId) {
              router.push('/index');
              activeSessionId.value=null;
            }

            ElMessage.success('删除成功');
          } else {
            ElMessage.error(res.msg || '删除失败');
          }
        } catch (error) {
          console.error("删除失败:", error);
          ElMessage.error("删除失败");
        }
      }).catch(() => {
      });
      break;
  }
};

// 开启新对话
const startNewChat = () => {
  router.push('/index');
  activeSessionId.value = null;
  inputMessage.value = ''; // 清空输入框
};

// 处理设置下拉菜单
const handleSettingCommand = (command) => {
  switch (command) {
    case 'profile':
      // 显示个人信息弹窗
      profileDialogVisible.value = true;
      break;
    case 'settings':
      ElMessage.info('打开系统设置');
      break;
    case 'contact':
      ElMessage.info('打开意见反馈');
      break;
    case 'logout':
      ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        removeToken();
        router.push('/login');
        ElMessage.success('已退出登录');
      }).catch(() => {
      });
      break;
  }
};

// 处理个人信息更新后的回调
const handleProfileUpdated = ({ nickname, avatar }) => {
  // 更新页面上显示的用户信息
  userName.value = nickname || userStore.getUserName();
  userImage.value = avatar;
  userAvatarSrc.value = avatar;
};


// 在组件挂载时初始化
onMounted(async () => {
  try {
    await initUserInfo();
    await getSession();

    // 如果路由中有会话ID，则打开对应会话
    if (route.params.sessionId) {
      activeSessionId.value = route.params.sessionId;
    }
  } catch (error) {
    console.error("初始化失败:", error);
  }
});
</script>

<style scoped>
/* 整体布局 */
.common-layout {
  display: flex;
  height: 100vh;
  background: #ffffff;
  overflow: hidden; /* 防止整个页面出现滚动条 */
}

/* 侧边栏样式 */
.sidebar {
  width: 260px;
  background: #2c56a0; /* 深蓝色 */
  display: flex;
  flex-direction: column;
  position: relative;
  transition: width 0.3s ease;
  height: 100vh; /* 确保高度等于视口高度 */
  overflow:hidden;
}

.sidebar.collapsed {
  width: 80px;
}

.sidebar-top {
  display: flex;
  flex-direction: column;
  flex: 1; /* 占用除用户资料外的所有空间 */
  overflow: hidden; /* 防止内容溢出 */
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px;
  flex-shrink: 0; /* 防止标题被压缩 */
}

.sidebar-title {
  color: white;
  font-size: 24px;
  margin: 0;
  font-weight: 600;
}

.collapse-btn {
  width: 28px;
  height: 28px;
  background: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2c56a0;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  margin-left: 12px;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

/* 新对话按钮 */
.new-chat-btn {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.12);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  margin: 0 16px;
  border-radius: 20px;
  flex-shrink: 0; /* 防止按钮被压缩 */
}

.new-chat-btn:hover {
  background: rgba(255, 255, 255, 0.18);
}

/* 历史记录样式 */
.chat-history {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 0 16px;
  flex: 1; /* 占用剩余空间 */
  overflow-y: auto; /* 只有历史记录允许滚动 */
  overflow-x:hidden;
  margin-bottom: 10px; /* 为底部用户信息留出空间 */
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 标题和操作分别居左和居右 */
  padding: 8px 12px;
  color: white;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.history-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.history-item.active {
  background: rgba(255, 255, 255, 0.2);
  font-weight: 500;
}

.history-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  opacity: 0.7;
  transition: opacity 0.2s ease;
}

.history-item:hover .history-actions {
  opacity: 1;
}

.more-icon {
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.more-icon:hover {
  background: rgba(255, 255, 255, 0.1);
}

.history-time {
  font-size: 12px;
}

/* 用户信息 */
.user-profile {
  position: relative;
  padding: 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  flex-shrink: 0; /* 防止用户信息被压缩 */
  background-color: #2c56a0; /* 确保与侧边栏背景一致 */
  z-index: 10; /* 确保用户信息在历史记录上层 */
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  color: white;
  transition: background-color 0.2s;
}

.dropdown-trigger:hover {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  padding: 4px;
  margin: -4px;
}

.arrow-icon {
  margin-left: auto;
  font-size: 14px;
  opacity: 0.7;
  transition: transform 0.3s;
}

.dropdown-trigger:hover .arrow-icon {
  transform: rotate(180deg);
}

/* 用户头像样式 */
.user-img {
  display: inline-block !important;
  background-color: #f0f0f0 !important;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
  border: 2px solid #ffffff !important;
  object-fit: cover !important;
  flex-shrink: 0; /* 防止头像被压缩 */
}

.user-info {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 0;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f0f5ff; /* 浅蓝背景 */
  overflow: hidden;
}

/* Element Plus 下拉菜单样式覆盖 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 4px;
}

/* 确保头像内部文字正确显示 */
:deep(.el-avatar > span) {
  line-height: 32px;
  font-size: 16px;
  font-weight: bold;
  color: #2c56a0;
}

/* 修复折叠后的显示问题 */
.sidebar.collapsed .new-chat-btn {
  justify-content: center;
  padding: 12px 8px;
}

.sidebar.collapsed .user-profile {
  display: flex;
  justify-content: center;
}

/* 滚动条自定义样式 */
.chat-history::-webkit-scrollbar {
  width: 5px;
}

.chat-history::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
}

.chat-history::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 10px;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}
</style>